package com.bishe.bishe.Controller;

import com.alibaba.fastjson.JSON;
import com.bishe.bishe.Service.CommentService;
import com.bishe.bishe.Service.CustomerService;
import com.bishe.bishe.Service.OrderService;
import com.bishe.bishe.Service.OrderdetailService;
import com.bishe.bishe.pojo.Advertisements;
import com.bishe.bishe.entity.Detail;
import com.bishe.bishe.entity.WxDetail;
import com.bishe.bishe.pojo.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping("/order")
@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderdetailService orderdetailService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private CustomerService customerService;

    @RequestMapping("/findall")
    public PageInfo<Orders> findall(@DefaultValue("1") int page,@DefaultValue("10") int size){
        PageInfo<Orders> findall=orderService.findall(page, size) ;
    return findall;
    }
    @RequestMapping("/findPage")
    public PageInfo<Orders> findPage(@RequestBody Map<String,Object> searchMap, @DefaultValue("1") int page,@DefaultValue("10") int size,@Validated @RequestParam(name = "stateName",required = false) String stateName){
        return orderService.findPage(searchMap, page, size,stateName);
    }

    @RequestMapping("/getnumber")
    public List<Double> getnumber() throws ParseException {
        List<Double> ints=new ArrayList();
        List <Orders> unsure = orderService.findstate("未确认");
       ints.add((double) unsure.size());//0
        List <Orders> sure = orderService.findstate("已确认");
        ints.add((double) sure.size());//1
        List <Orders> cancel = orderService.findstate("申请取消");
        ints.add((double) cancel.size());//2
        List <Orders> finish = orderService.findstate("已完成");
        ints.add((double) finish.size());//3
        List <Comments> findnumber = commentService.findnumber();
        ints.add((double) findnumber.size());//4未回复
        int findexpress = orderService.findexpress();
        ints.add((double) findexpress);//5需要配送
        List <Orders> count = orderService.count();
        Double money=0.0;
        for (int i=0;i<count.size();i++){
            money=money+count.get(i).getOrderTotal();
        }
        ints.add((double) count.size());//6昨日完成订单
        ints.add(money);//7昨日完成金额
        List <Customer> count1 = customerService.count();
        ints.add((double) count1.size());//8昨日用户量
        return ints;
    }

    @RequestMapping("/updateAdvertisement")
    public int updateAdvertisement(@Validated@RequestParam(name = "advertisemant",required = false)String advertisement){
        return orderService.updateAdvertisement(advertisement);
    }
    @RequestMapping("/findAdvert")
    public  Advertisements findAdvertisement(){
        return orderService.selectAdvert().get(0);
    }

    @RequestMapping("/update")
    public int update(@RequestBody Orders orders){
        return orderService.update(orders);
    }

    @RequestMapping("/findstate")
    public PageInfo<Orders> findstate(@Validated @RequestParam(name = "stateName",required = false) String stateName,int page, int size){
        return orderService.findstate(stateName,page, size);
    }


    @RequestMapping("/finddetail")
    public List<Detail> finddetail(@Validated @RequestParam(name = "orderId",required = false) Long orderId) throws ParseException {
        List<Detail> list=new ArrayList <>();
            List<Orderdetail> orderdetail = orderdetailService.findOrderdetail(orderId);
            if (orderdetail.size()!=1) {
                for (int j = 0; j <orderdetail.size(); j++) {
                    int sum=orderdetail.get(j).getOrderdetailNumber();
                    for (int k = j + 1; k < orderdetail.size(); k++) {
                        if (orderdetail.get(j).getSpecies().getSpeciesId()==orderdetail.get(k).getSpecies().getSpeciesId()) {
                            sum=sum + orderdetail.get(k).getOrderdetailNumber();
                            orderdetail.remove(k);
                            k--;
                        }
                    }
                    Detail detail=new Detail();
                    detail.setPrice(orderdetail.get(j).getSpecies().getSpeciesPrice());
                    detail.setOrderdetailNumber(sum);
                    detail.setSpeciesName(orderdetail.get(j).getSpecies().getSpeciesName());
                    detail.setUnitName(orderdetail.get(j).getSpecies().getUnit().getUnitNumber());
                    detail.setTaketime(orderdetail.get(j).getOrders().getOrderTaketime());
                    detail.setOrdertime(orderdetail.get(j).getOrders().getOrderTime());
                    detail.setExpress(orderdetail.get(j).getOrders().getExpress().getExpressName());
                    detail.setLocation(orderdetail.get(j).getOrders().getCustomer().getCustomerLocation());
                    detail.setNumber(orderdetail.get(j).getOrders().getCustomer().getCustomerNumber());
                    detail.setSpeciesImg(orderdetail.get(j).getSpecies().getSpeciesImg());
                    detail.setRemarks(orderdetail.get(j).getOrders().getOrderRemarks());
                    detail.setIdentify(orderdetail.get(j).getOrders().getOrderIdentify());
                    list.add(detail);
                }
                return list;
            }else {
                Detail detail=new Detail();
                detail.setPrice(orderdetail.get(0).getSpecies().getSpeciesPrice());
                detail.setOrderdetailNumber(orderdetail.get(0).getOrderdetailNumber());
                detail.setSpeciesName(orderdetail.get(0).getSpecies().getSpeciesName());
                detail.setUnitName(orderdetail.get(0).getSpecies().getUnit().getUnitNumber());
                detail.setTaketime(orderdetail.get(0).getOrders().getOrderTaketime());
                detail.setOrdertime(orderdetail.get(0).getOrders().getOrderTime());
                detail.setExpress(orderdetail.get(0).getOrders().getExpress().getExpressName());
                detail.setLocation(orderdetail.get(0).getOrders().getCustomer().getCustomerLocation());
                detail.setNumber(orderdetail.get(0).getOrders().getCustomer().getCustomerNumber());
                detail.setSpeciesImg(orderdetail.get(0).getSpecies().getSpeciesImg());
                detail.setRemarks(orderdetail.get(0).getOrders().getOrderRemarks());
                detail.setIdentify(orderdetail.get(0).getOrders().getOrderIdentify());
                list.add(detail);
                return list;
            }
    }


    @RequestMapping("/batchupdate")
    public int batchupdate(@Validated @RequestBody List<Integer> idlist){
        State state=new State();
        state.setStateName("已确认");
        for (int i = 0; i < idlist.size(); i++) {
            Orders orders=new Orders();
            orders.setOrderId(Long.valueOf(idlist.get(i)));
            orders.setState(state);
            orderService.update(orders);
        }
        return 1;
    }


    @RequestMapping("/checkbyId")
    public int checkbyId(@Validated @RequestParam(name = "orderId",required = false) Long orderId,@Validated @RequestParam(name = "checkId",required = false) int checkId) throws ParseException {
        Orders byId = orderService.findByIdcheckId(orderId,checkId);
        if (checkId==byId.getOrderIdentify()) {
            return 1;
        } else {
            return 0;
        }
    }

    @RequestMapping("/check")
    public List<Detail> check(@Validated @RequestParam(name = "customerNumber",required = false) String customerNumber,@Validated @RequestParam(name = "orderIdentify",required = false) int orderIdentify) throws ParseException {
        List <Orders> byCheck = orderService.findByCheck(customerNumber, orderIdentify);
        if (byCheck.size()!=0) {
            if (byCheck.get(0).getState().getStateName().equals("已确认")) {
                return  finddetail(byCheck.get(0).getOrderId());
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @RequestMapping("/sure")
    public Long sure(@Validated @RequestParam(name = "customerNumber",required = false) String customerNumber,@Validated @RequestParam(name = "orderIdentify",required = false) int orderIdentify) throws ParseException {
        List <Orders> byCheck = orderService.findByCheck(customerNumber, orderIdentify);
        int i = checkbyId(byCheck.get(0).getOrderId(), orderIdentify);
        if (i==1){
            return byCheck.get(0).getOrderId();
        }else {
            return Long.valueOf(0);
        }
    }

    @RequestMapping("/findByWx")
    public List<Orders> findByWx(@Validated @RequestParam(name = "customerNumber",required = false) String customerNumber){
        return orderService.findByWx(customerNumber);
    }

    @RequestMapping("/insertOrder")
    public int insertOrder(@Validated @RequestBody Map<String,Object> multiIndex){
        Orders orders=new Orders();
        java.util.Date date=new java.util.Date();
        long l = date.getTime();
        java.sql.Date sqlDate=new java.sql.Date(l);
        orders.setOrderTime(sqlDate);//设置下单时间
        Customer customer=new Customer();
        customer.setCustomerId((Integer) multiIndex.get("customer"));//设置客户id
        customer.setCustomerLocation((String) multiIndex.get("location"));
        orders.setCustomer(customer);
        Express express=new Express();
        if ((Integer) multiIndex.get("send")==0){
            express.setExpressName("不");
        }else {
            express.setExpressName("要");
            customerService.update(customer);
        };
        int identify= (int) ((Math.random()*9+1)*1000);
        orders.setOrderIdentify(identify);//设置随机验证码
        orders.setExpress(express);//设置要不要送
         ArrayList<Integer> mul= (ArrayList <Integer>) multiIndex.get("multiIndex");
        if (multiIndex.get("money") instanceof Integer){
            Integer a= (Integer) multiIndex.get("money");
            orders.setOrderTotal(a.doubleValue());
        }else {
            orders.setOrderTotal((Double) multiIndex.get("money"));//设置多少钱
        };
        String ordertime;
        if (mul.get(0)==0){
            if (mul.get(1)==0){
                ordertime="明天上午7点-11点";
            }else {
                ordertime="明天下午1点-6点";
            }
        }else {
            if (mul.get(1)==0){
                ordertime="后天上午7点-11点";
            }else {
                ordertime="后台下午1点-6点";
            }
        }
        orders.setOrderTaketime(ordertime);
        orders.setOrderRemarks((String) multiIndex.get("remarks"));
        //将goods转成wxDetil类型
        String goods=JSON.toJSONString(multiIndex.get("goods"));
        List <WxDetail> wxDetails = JSON.parseArray(goods, WxDetail.class);
        int insert = orderService.insert(orders);
        Orders orders1=new Orders();
        orders1.setOrderId(orders.getOrderId());
        Species species=new Species();
        Orderdetail orderdetail=new Orderdetail();
        orderdetail.setOrders(orders1);
        for (int i=0;i<wxDetails.size();i++){
            species.setSpeciesId(wxDetails.get(i).getId());
            orderdetail.setSpecies(species);
            orderdetail.setOrderdetailNumber(wxDetails.get(i).getNum());
            orderdetailService.insert(orderdetail);
        }
        if (insert==1){
            return 1;
        }else {
       return  0;
        }
    }

    @RequestMapping("/indexinsert")
    public int indexinsert(@Validated @RequestBody Map<String,Object> multiIndex){
//        System.out.println("(int) ((Math.random()*9+1)*1000)"+(int) ((Math.random()*9+1)*1000));
        Orders orders=new Orders();
        java.util.Date date=new java.util.Date();
        long l = date.getTime();
        java.sql.Date sqlDate=new java.sql.Date(l);
        orders.setOrderTime(sqlDate);//设置下单时间
        Customer customer=new Customer();
        customer.setCustomerId((Integer) multiIndex.get("customer"));//设置客户id
        customer.setCustomerLocation((String) multiIndex.get("location"));//设置地址
        orders.setCustomer(customer);
        Express express=new Express();
        if ((Integer) multiIndex.get("send")==0){
            express.setExpressName("不");
        }else {
            express.setExpressName("要");
            customerService.update(customer);
        };
        orders.setExpress(express);//设置要不要送
        int identify= (int) ((Math.random()*9+1)*1000);
        orders.setOrderIdentify(identify);//设置随机验证码
        //设置钱
        if (multiIndex.get("money") instanceof Integer){
            Integer a= (Integer) multiIndex.get("money");
            orders.setOrderTotal(a.doubleValue());
        }else {
            orders.setOrderTotal((Double) multiIndex.get("money"));
        };
        orders.setOrderRemarks((String) multiIndex.get("remarks"));//添加备注
        //将goods转成wxDetil类型
        String goods=JSON.toJSONString(multiIndex.get("goods"));
        List <WxDetail> wxDetails = JSON.parseArray(goods, WxDetail.class);
        int insert = orderService.indexinsert(orders);
        Orders orders1=new Orders();
        orders1.setOrderId(orders.getOrderId());
        Species species=new Species();
        Orderdetail orderdetail=new Orderdetail();
        orderdetail.setOrders(orders1);
        for (int i=0;i<wxDetails.size();i++){
            species.setSpeciesId(wxDetails.get(i).getId());
            orderdetail.setSpecies(species);
            orderdetail.setOrderdetailNumber(wxDetails.get(i).getNum());
            orderdetailService.insert(orderdetail);
        }
        if (insert==1){
            return 1;
        }else {
            return  0;
        }
    }
}
